package cs757;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.Vector;

import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.EmptyBorder;

public class DlgAddStudentToProject extends JDialog {

	private static final long serialVersionUID = 394383263585433937L;

	private final JPanel contentPanel = new JPanel();
	
	private DefaultListModel list;
	
	//Database connection
	private DatabaseConnector conn;
	
	//Key of the project that we are adding this student to 
	private String recordID;
	
	private boolean ok = false;
	private JComboBox comboBoxStudents;
	private JComboBox comboBoxSponsor;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		try {
			DlgAddStudentToProject dialog = new DlgAddStudentToProject();
			dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
			dialog.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Create the dialog.
	 */
	public DlgAddStudentToProject() {
		setBounds(100, 100, 450, 300);
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		JLabel lblStudent = new JLabel("Add student:");
		JLabel lblSponsor = new JLabel("Choose sponsor:");
		comboBoxStudents = new JComboBox();
		comboBoxSponsor = new JComboBox();
		GroupLayout gl_contentPanel = new GroupLayout(contentPanel);
		gl_contentPanel.setHorizontalGroup(
			gl_contentPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPanel.createSequentialGroup()
					.addGap(24)
					.addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING)
						.addComponent(comboBoxStudents, GroupLayout.PREFERRED_SIZE, 178, GroupLayout.PREFERRED_SIZE)
						.addComponent(lblStudent))
					.addGap(18)
					.addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING)
						.addComponent(lblSponsor)
						.addComponent(comboBoxSponsor, GroupLayout.PREFERRED_SIZE, 177, GroupLayout.PREFERRED_SIZE))
					.addContainerGap(35, Short.MAX_VALUE))
		);
		gl_contentPanel.setVerticalGroup(
			gl_contentPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPanel.createSequentialGroup()
					.addGap(38)
					.addGroup(gl_contentPanel.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblSponsor)
						.addComponent(lblStudent))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(gl_contentPanel.createParallelGroup(Alignment.BASELINE)
						.addComponent(comboBoxStudents, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(comboBoxSponsor, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addContainerGap(145, Short.MAX_VALUE))
		);
		contentPanel.setLayout(gl_contentPanel);
		{
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
			getContentPane().add(buttonPane, BorderLayout.SOUTH);
			{
				JButton okButton = new JButton("OK");
				okButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent arg0) {
						addStudentToList();
						closeDialog();
					}
				});
				okButton.setActionCommand("OK");
				buttonPane.add(okButton);
				getRootPane().setDefaultButton(okButton);
			}
			{
				JButton cancelButton = new JButton("Cancel");
				cancelButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent arg0) {
						closeDialog();
					}
				});
				cancelButton.setActionCommand("Cancel");
				buttonPane.add(cancelButton);
			}
		}
	}
	
	/**
	 * Add the student to the project's list of students
	 * Insert a record for the student into the supervises table of the DB, and update the GUI list
	 */
	private void addStudentToList(){
	
		try {  
			String studentIDandName = (String)comboBoxStudents.getSelectedItem();
			String studentID = studentIDandName.substring(0, studentIDandName.indexOf('-'));
			String professorIDandName = (String)comboBoxSponsor.getSelectedItem();
			String professorID = professorIDandName.substring(0, professorIDandName.indexOf('-'));
			
			Object[] values = new Object[]{
					professorID,
					studentID,
					Integer.parseInt(recordID)
				};
			conn.executeInsert(DatabaseConnector.INSERT_GROUP_MEMBER_STUDENT, values);
			list.addElement(comboBoxStudents.getSelectedItem());

		} catch (SQLException e) {
			JOptionPane.showMessageDialog(null, "Error querying database.\nQuery:"+DatabaseConnector.INSERT_GROUP_MEMBER_STUDENT,
					"Error In Query", JOptionPane.ERROR_MESSAGE);
		}
	}
	
	/**
	 * Query the DB for the list of students and use the list to populate the students combo box
	 */
	protected void populateStudentComboBox(){
		try {
			Vector<Vector<Object>> results = conn.executeQuery(DatabaseConnector.STUDENT_WORKS_AVAILABLE, 2);
			
			for(Vector<Object> row:results){
				comboBoxStudents.addItem(row.get(0)+" - "+row.get(1));
			}
		} catch (SQLException e) {
			JOptionPane.showMessageDialog(null, "Error querying major IDs from department table.\n ",
					"Error In Query", JOptionPane.ERROR_MESSAGE);
		}
	}
	
	
	/**
	 * Query the DB for the list of professors and use the list to populate the professors (sponsors) combo box
	 */
	protected void populateProfessorComboBox(){
		try {
			Vector<Vector<Object>> results = conn.executeQuery(DatabaseConnector.PROFESSOR_WORKS_QUERY+recordID, 2);
			
			for(Vector<Object> row:results){
				comboBoxSponsor.addItem(row.get(0)+" - "+row.get(1));
			}
		} catch (SQLException e) {
			JOptionPane.showMessageDialog(null, "Error querying major IDs from department table.\n ",
					"Error In Query", JOptionPane.ERROR_MESSAGE);
		}
	}
	
	/**
	 * Can only add students to a project if they have a sponsor, so 
	 * check to make sure the project first has some professors working on it
	 * who can function as sponsors
	 * @return
	 */
	protected boolean checkIfSponsorsAvailable(){
		if (comboBoxSponsor.getItemCount() <= 0){
			JOptionPane.showMessageDialog(null, "Each project must have at least one professor working on it who can sponsor a student's work.\n " +
					"Please add a professor to the project first.",
					"No sponsors", JOptionPane.ERROR_MESSAGE);
			return false;
		}
		return true;
	}
	
	/**
	 * Set the list model for the student combo box
	 * @param list
	 */
	public void setList(DefaultListModel list){
		this.list = list;
	}
	

	/**
	 * Close the add student GUI
	 */
	private void closeDialog(){
		this.setVisible(false);
	}

	/**
	 * @return the ok
	 */
	public boolean isOk() {
		return ok;
	}

	/**
	 * @param conn the conn to set
	 */
	public void setConn(DatabaseConnector conn) {
		this.conn = conn;
	}
	
	/**
	 * @param recordID the recordID to set
	 */
	public void setRecordID(String recordID) {
		this.recordID = recordID;
	}

}
